<template>
  <div>
    <div class="search__example--wrap">
      <com-search
        :data="searchData"
        @search-submit="searchSubmit"
        @reset-submit="resetSubmit"
      />
    </div>

    <div class="button__example--wrap">
      <el-button type="primary" icon="el-icon-circle-plus-outline" @click="open(false, 'InfoWrite')">新增</el-button>
      <el-button
        type="danger"
        icon="el-icon-delete"
        @click="dels"
      >退款</el-button>
    </div>

    <com-table
      v-loading="loading"
      selection
      :columns="columns"
      :data="tableData"
      :pagination="{
        currentPage: defalutParams.pageIndex,
        total: total,
        onSizeChange: handleSizeChange,
        onCurrentChange: handleCurrentChange
      }"
      @selection-change="handleSelectionChange"
    >
      <template #status="scope">
        <el-tag
          :type="scope.row.status === 0
            ? 'success'
            : (scope.row.status === 1
              ? 'warning'
              : 'danger')"
        >{{ scope.row.status === 0
          ? '未支付'
          : (scope.row.status === 1
            ? '已支付'
            : '已退款') }}
        </el-tag>
      </template>
      <template #action="scope">
        <el-button type="primary" :disabled="scope.row.status!==0" size="mini" @click="open(scope.row, 'FacePay')">当面付</el-button>
        <el-button type="success" :disabled="scope.row.status!==0" size="mini" @click="getAliDet(scope.row.id)">网站支付</el-button>
<!--        <el-button type="success" :disabled="scope.row.status!==0" size="mini" @click="getHuaBeiDet(scope.row.id)">花呗分期</el-button>-->
        <el-button type="danger" :disabled="scope.row.status!==1" size="mini" @click="dels(scope.row)">退款</el-button>
      </template>
    </com-table>

    <com-dialog v-model="dialogVisible" :title="title">
      <info-write
        v-if="comName === 'InfoWrite'"
        :info="info"
        @close="toggleVisible"
        @success="success"
      />
      <face-pay
        v-if="comName === 'FacePay'"
        :info="info"
        @close="toggleVisible"
        @success="success"
      />
      <detail
        v-if="comName === 'Detail'"
        :info="info"
        @close="toggleVisible"
      />
    </com-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import InfoWrite from './components/InfoWrite.vue'
import Detail from './components/Detail.vue'
import FacePay from './components/FacePay.vue'
import { useExample } from '@/hooks/useExample'
import { Message } from '_c/Message'

import { getListApi, delsApi, nativePayApi, huaBeiPayApi } from './api'
import { formatTime } from '@/utils'

const searchData = [
  {
    label: '订单编号',
    value: '',
    itemType: 'input',
    field: 'title',
    placeholder: '请输入订单编号',
    clearable: true
  },
  {
    label: '订单状态',
    value: '',
    itemType: 'select',
    field: 'status',
    options: [{
      title: '未支付',
      value: '0'
    }, {
      title: '已支付',
      value: '1'
    }]
  }
]

const columns = [
  {
    field: 'createTime',
    label: '下单时间',
    formatter: (row: any, column: any, cellValue: any, index: number) => {
      return formatTime(row.createTime, 'yyyy-MM-dd HH:mm:ss')
    }

  },
  {
    field: 'outTradeNo',
    label: '订单编号'
  },
  {
    field: 'subject',
    label: '标题',
    showOverflowTooltip: true
  },

  {
    field: 'status',
    label: '订单状态',
    slots: {
      default: 'status'
    }
  },
  {
    field: 'totalAmount',
    label: '付款金额'
  },
  {
    field: 'action',
    label: '操作',
    width: '340px',
    slots: {
      default: 'action'
    }
  }
]

export default defineComponent({
  // name: 'ExampleDialog',
  components: {
    InfoWrite,
    Detail,
    FacePay
  },
  setup() {
    const info = ref<any>(null)

    const {
      defalutParams,
      tableData,
      loading,
      total,
      dialogVisible,
      title,
      currentChange,
      sizeChange,
      handleSelectionChange,
      selectionData,
      delData,
      comName,
      toggleVisible
    } = useExample()

    // 请求数据
    async function getExampleList(data?: any): Promise<void> {
      try {
        const res = await getListApi({
          params: Object.assign(defalutParams, data || {})
        })
        total.value = res.totalElements
        tableData.value = res.content
      } finally {
        loading.value = false
      }
    }

    // 查询
    function searchSubmit(data: any) {
      // 该方法重置了一些默认参数
      currentChange(1)
      getExampleList(data)
    }

    // 重置
    function resetSubmit(data: any) {
      // 该方法重置了一些默认参数
      currentChange(1)
      getExampleList(data)
    }

    // 展示多少条
    function handleSizeChange(val: number) {
      // 该方法重置了一些默认参数
      sizeChange(val)
      getExampleList()
    }

    // 展示第几页
    function handleCurrentChange(val: number) {
      // 该方法重置了一些默认参数
      currentChange(val)
      getExampleList()
    }

    // 删除多选
    function dels(item?: any) {
      delData(async() => {
        let ids: number[] = []
        if (item.id) {
          ids.push(item.id)
        } else {
          ids = selectionData.value.map((v: any) => {
            return v.id
          })
        }
        const res = await delsApi({
          data: JSON.stringify(ids)
        })
        if (res.status === 200) {
          Message.success(res.message)
          getExampleList()
        }
      }, { hiddenVerify: item.id, text: '此操作将申请退款, 是否继续?' })
    }

    // 打开弹窗
    function open(row: any, component: string) {
      comName.value = component
      title.value = !row ? '新增' : (component === 'Detail' ? '刷脸付' : '当面付（打开支付宝扫一扫）')
      info.value = row || null
      toggleVisible(true)
    }

    // 成功之后的回调
    function success(type: string) {
      if (type === 'add') {
        currentChange(1)
      }
      toggleVisible()
      getExampleList()
    }

    getExampleList()

    // 调用支付宝网站支付
    async function getAliDet(id: number) {
      try {
        const res = await nativePayApi({
          params: {
            id: id
          }
        })
        if (res.status === 200) {
          const body = document.querySelector('body')
          if (body != null) {
            body.innerHTML = res.message // 查找到当前页面的body，将后台返回的form替换掉他的内容
          }
          document.forms[0].setAttribute('target', '_blank') // 新开窗口跳转
          document.forms[0].submit() // 执行submit表单提交，让页面重定向，跳转到支付宝页面
        }
      } catch (e) {
        console.log(e)
      }
    }
    // 调用支付宝花呗分期支付
    async function getHuaBeiDet(id: number) {
      try {
        const res = await huaBeiPayApi({
          params: {
            id: id
          }
        })
        if (res.status === 200) {
          console.info('返回信息：', res)
        }
      } catch (e) {
        console.log(e)
      }
    }

    return {
      info, open,
      searchData, searchSubmit, resetSubmit,
      columns,
      defalutParams,
      loading,
      tableData,
      total,
      title,
      dialogVisible,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      dels,
      close, success,
      comName,
      toggleVisible,
      getAliDet,
      getHuaBeiDet
    }
  }
})
</script>

<style>
</style>
